package utils

import (
	"bytes"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"github.com/beego/beego/v2/core/config"
	"github.com/disintegration/imaging"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/astaxie/beego"
	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"github.com/nfnt/resize"
	"github.com/unidoc/unidoc/pdf/creator"
	pdf "github.com/unidoc/unidoc/pdf/model"
)

var (
	Ossurl          = "http://img.sdwanzheng.com/tcp/conf/"
	fontTypes       *truetype.Font
	fontSize        = float64(10)
	AccessKeyId     = "LTAI7h84z4fwCZ4a"
	AccessKeySecret = "bcD7thXdr2iwQqoR59GXE2OMcoEJ33"

	NewStagePosition = map[string]map[string]float64{
		"name":       map[string]float64{"x": 120.0, "y": 135.6, "w": 100.0},
		"sex":        map[string]float64{"x": 255.2, "y": 135.6, "w": 30.0},
		"idcard":     map[string]float64{"x": 425.2, "y": 135.6, "w": 200.0},
		"address":    map[string]float64{"x": 120.2, "y": 160.6, "w": 82.6},
		"phone":      map[string]float64{"x": 580.2, "y": 160.6, "w": 200.0},
		"photo":      map[string]float64{"x": 730.3, "y": 125.5, "w": 60.6},
		"sdate":      map[string]float64{"x": 655.2, "y": 135.6, "w": 200.0},
		"stunum":     map[string]float64{"x": 705.2, "y": 110.8, "w": 200.0},
		"signyear1":  map[string]float64{"x": 510.2, "y": 272.5, "w": 200.0},
		"signyear2":  map[string]float64{"x": 510.2, "y": 330.5, "w": 200.0},
		"signyear3":  map[string]float64{"x": 510.2, "y": 388.5, "w": 200.0},
		"signyear4":  map[string]float64{"x": 510.2, "y": 446.5, "w": 200.0},
		"A1":         map[string]float64{"x": 130.2, "y": 185.6, "w": 8.0},
		"A2":         map[string]float64{"x": 170.2, "y": 185.6, "w": 8.0},
		"A3":         map[string]float64{"x": 207.2, "y": 185.6, "w": 8.0},
		"B1":         map[string]float64{"x": 244.2, "y": 185.6, "w": 8.0},
		"B2":         map[string]float64{"x": 281.2, "y": 185.6, "w": 8.0},
		"C1":         map[string]float64{"x": 318.2, "y": 185.6, "w": 8.0},
		"C2":         map[string]float64{"x": 357.2, "y": 185.6, "w": 8.0},
		"C3":         map[string]float64{"x": 395.2, "y": 185.6, "w": 8.0},
		"C4":         map[string]float64{"x": 432.2, "y": 185.6, "w": 8.0},
		"C5":         map[string]float64{"x": 470.2, "y": 185.6, "w": 8.0},
		"C6":         map[string]float64{"x": 508.0, "y": 185.6, "w": 8.0},
		"D":          map[string]float64{"x": 541.2, "y": 185.6, "w": 8.0},
		"E":          map[string]float64{"x": 572.2, "y": 185.6, "w": 8.0},
		"F":          map[string]float64{"x": 601.2, "y": 185.6, "w": 8.0},
		"M":          map[string]float64{"x": 634.2, "y": 185.6, "w": 8.0},
		"N":          map[string]float64{"x": 668.2, "y": 185.6, "w": 8.0},
		"P":          map[string]float64{"x": 700.2, "y": 185.6, "w": 8.0},
		"s1thrhours": map[string]float64{"x": 120.0, "y": 250.6, "w": 200.0},
		"s2thrhours": map[string]float64{"x": 120.2, "y": 310.6, "w": 200.0},
		"s3thrhours": map[string]float64{"x": 120.2, "y": 370.6, "w": 200.0},
		"s4thrhours": map[string]float64{"x": 120.2, "y": 430.6, "w": 200.0},
	}

	StagePosition = map[string]map[string]float64{
		"name":       map[string]float64{"x": 155.2, "y": 92.6, "w": 100.0},
		"sex":        map[string]float64{"x": 255.2, "y": 92.6, "w": 30.0},
		"cardtype":   map[string]float64{"x": 360.2, "y": 92.6, "w": 100.0},
		"idcard":     map[string]float64{"x": 530.2, "y": 92.6, "w": 200.0}, // photo.SetPos(675.3, 83.5) photo.ScaleToWidth(82.6)
		"address":    map[string]float64{"x": 155.2, "y": 125.6, "w": 82.6},
		"phone":      map[string]float64{"x": 465.2, "y": 125.6, "w": 200.0},
		"photo":      map[string]float64{"x": 675.3, "y": 83.5, "w": 82.6},
		"traintype":  map[string]float64{"x": 155.2, "y": 160.6, "w": 200.0},
		"sdate":      map[string]float64{"x": 465.2, "y": 160.6, "w": 200.0},
		"stunum":     map[string]float64{"x": 650.2, "y": 67.8, "w": 200.0},
		"signyear1":  map[string]float64{"x": 522.2, "y": 268.5, "w": 200.0},
		"signyear2":  map[string]float64{"x": 522.2, "y": 342.5, "w": 200.0},
		"signyear3":  map[string]float64{"x": 522.2, "y": 414.5, "w": 200.0},
		"signyear4":  map[string]float64{"x": 522.2, "y": 486.5, "w": 200.0},
		"s1thrhours": map[string]float64{"x": 175.2, "y": 250.6, "w": 200.0},
		"s2thrhours": map[string]float64{"x": 175.2, "y": 320.6, "w": 200.0},
		"s3thrhours": map[string]float64{"x": 175.2, "y": 390.6, "w": 200.0},
		"s4thrhours": map[string]float64{"x": 175.2, "y": 460.6, "w": 200.0},
		"p1mil":      map[string]float64{"x": 255.2, "y": 250.6, "w": 200.0},
		"p2mil":      map[string]float64{"x": 255.2, "y": 320.6, "w": 200.0},
		"p3mil":      map[string]float64{"x": 255.2, "y": 390.6, "w": 200.0},
		"p4mil":      map[string]float64{"x": 255.2, "y": 460.6, "w": 200.0},
		"s1result":   map[string]float64{"x": 335.2, "y": 250.6, "w": 200.0},
		"s2result":   map[string]float64{"x": 335.2, "y": 320.6, "w": 200.0},
		"s3result":   map[string]float64{"x": 335.2, "y": 390.6, "w": 200.0},
		"s4result":   map[string]float64{"x": 335.2, "y": 460.6, "w": 200.0},
		"p1exam":     map[string]float64{"x": 415.2, "y": 250.6, "w": 200.0},
		"p2exam":     map[string]float64{"x": 415.2, "y": 320.6, "w": 200.0},
		"p3exam":     map[string]float64{"x": 415.2, "y": 390.6, "w": 200.0},
		"p4exam":     map[string]float64{"x": 415.2, "y": 460.6, "w": 200.0},
		"signature1": map[string]float64{"x": 525.0, "y": 224.6, "w": 65.0}, //525.0, 224.6
		"signature2": map[string]float64{"x": 525.0, "y": 294.6, "w": 65.0}, //525.0, 294.6
		"signature3": map[string]float64{"x": 525.0, "y": 364.6, "w": 65.0}, //525.0, 364.6
		"signature4": map[string]float64{"x": 525.0, "y": 434.6, "w": 65.0}, //525.0, 434.6
	}
	GraduationPosition = map[string]map[string]float64{
		"username":    map[string]float64{"x": 160.0, "y": 250.0, "w": 60.0},
		"sex":         map[string]float64{"x": 265.0, "y": 250.0, "w": 105.0},
		"signyear":    map[string]float64{"x": 337.0, "y": 250.0, "w": 105.0},
		"signmonth":   map[string]float64{"x": 397.0, "y": 250.0, "w": 105.0},
		"signday":     map[string]float64{"x": 447.0, "y": 250.0, "w": 105.0},
		"gradyear":    map[string]float64{"x": 95.0, "y": 273.0, "w": 105.0},
		"gradmonth":   map[string]float64{"x": 155.0, "y": 273.0, "w": 105.0},
		"gradday":     map[string]float64{"x": 205.0, "y": 273.0, "w": 105.0},
		"jointype":    map[string]float64{"x": 280.0, "y": 273.0, "w": 105.0},
		"footyear":    map[string]float64{"x": 310.0, "y": 360.0, "w": 105.0},
		"footmonth":   map[string]float64{"x": 370.0, "y": 360.0, "w": 105.0},
		"footday":     map[string]float64{"x": 425.0, "y": 360.0, "w": 105.0},
		"province":    map[string]float64{"x": 115.0, "y": 375.0, "w": 105.0},
		"photo":       map[string]float64{"x": 427.0, "y": 143.5, "w": 75.0},
		"signature1":  map[string]float64{"x": 360.0, "y": 182.6, "w": 85.0},
		"stunum":      map[string]float64{"x": 140.0, "y": 183.0, "w": 105.0},
		"school_name": map[string]float64{"x": 310.0, "y": 335.0, "w": 105.0},
	}
	ShanDongGraduationPosition = map[string]map[string]float64{
		"stunum":      map[string]float64{"x": 200.0, "y": 150.0, "w": 105.0},
		"username":    map[string]float64{"x": 180.0, "y": 185.0, "w": 60.0},
		"sex":         map[string]float64{"x": 280.0, "y": 185.0, "w": 105.0},
		"signyear":    map[string]float64{"x": 140.0, "y": 213.0, "w": 105.0},
		"signmonth":   map[string]float64{"x": 190.0, "y": 213.0, "w": 105.0},
		"signday":     map[string]float64{"x": 220.0, "y": 213.0, "w": 105.0},
		"gradyear":    map[string]float64{"x": 275.0, "y": 213.0, "w": 105.0},
		"gradmonth":   map[string]float64{"x": 320.0, "y": 213.0, "w": 105.0},
		"gradday":     map[string]float64{"x": 350.0, "y": 213.0, "w": 105.0},
		"jointype":    map[string]float64{"x": 150.0, "y": 230.0, "w": 105.0},
		"jointype1":   map[string]float64{"x": 150.0, "y": 240.0, "w": 105.0},
		"school_name": map[string]float64{"x": 320.0, "y": 300.0, "w": 105.0},
		"footyear":    map[string]float64{"x": 310.0, "y": 320.0, "w": 135.0},
		"footmonth":   map[string]float64{"x": 360.0, "y": 320.0, "w": 105.0},
		"footday":     map[string]float64{"x": 400.0, "y": 320.0, "w": 105.0},
		"photo":       map[string]float64{"x": 390.5, "y": 135.5, "w": 75.0},
		"signature1":  map[string]float64{"x": 320.0, "y": 130.0, "w": 85.0},
	}
	ShanXiGraduationPosition = map[string]map[string]float64{
		"stunum":     map[string]float64{"x": 150.0, "y": 134.0, "w": 105.0}, //1
		"photo":      map[string]float64{"x": 430.0, "y": 105.0, "w": 70.0},  //1
		"username":   map[string]float64{"x": 170.0, "y": 200.0, "w": 60.0},
		"sex":        map[string]float64{"x": 250.0, "y": 200.0, "w": 105.0},
		"idnum":      map[string]float64{"x": 350.0, "y": 200.0, "w": 105.0},
		"signyear":   map[string]float64{"x": 105.0, "y": 225.0, "w": 80.0},
		"signmonth":  map[string]float64{"x": 150.0, "y": 225.0, "w": 95.0},
		"signday":    map[string]float64{"x": 180.0, "y": 225.0, "w": 95.0},
		"gradyear":   map[string]float64{"x": 215.0, "y": 225.0, "w": 95.0},
		"gradmonth":  map[string]float64{"x": 260.0, "y": 225.0, "w": 95.0},
		"gradday":    map[string]float64{"x": 290.0, "y": 225.0, "w": 95.0},
		"jointype":   map[string]float64{"x": 350.0, "y": 225.0, "w": 105.0},
		"jointype1":  map[string]float64{"x": 350.0, "y": 225.0, "w": 105.0},
		"faren":      map[string]float64{"x": 190.0, "y": 260.0, "w": 85.0},
		"footyear":   map[string]float64{"x": 365.0, "y": 304.0, "w": 135.0},
		"footmonth":  map[string]float64{"x": 420.0, "y": 304.0, "w": 105.0},
		"footday":    map[string]float64{"x": 450.0, "y": 304.0, "w": 105.0},
		"signature1": map[string]float64{"x": 390.0, "y": 250.0, "w": 85.0},
	}
	ChengDeGraduationPosition = map[string]map[string]float64{
		"stunum":     map[string]float64{"x": 150.0, "y": 134.0, "w": 105.0}, //1
		"photo":      map[string]float64{"x": 430.0, "y": 105.0, "w": 70.0},  //1
		"username":   map[string]float64{"x": 170.0, "y": 200.0, "w": 60.0},
		"sex":        map[string]float64{"x": 250.0, "y": 200.0, "w": 105.0},
		"idnum":      map[string]float64{"x": 350.0, "y": 200.0, "w": 105.0},
		"signyear":   map[string]float64{"x": 105.0, "y": 225.0, "w": 80.0},
		"signmonth":  map[string]float64{"x": 150.0, "y": 225.0, "w": 95.0},
		"signday":    map[string]float64{"x": 180.0, "y": 225.0, "w": 95.0},
		"gradyear":   map[string]float64{"x": 215.0, "y": 225.0, "w": 95.0},
		"gradmonth":  map[string]float64{"x": 260.0, "y": 225.0, "w": 95.0},
		"gradday":    map[string]float64{"x": 290.0, "y": 225.0, "w": 95.0},
		"jointype":   map[string]float64{"x": 350.0, "y": 225.0, "w": 105.0},
		"jointype1":  map[string]float64{"x": 350.0, "y": 225.0, "w": 105.0},
		"faren":      map[string]float64{"x": 190.0, "y": 260.0, "w": 85.0},
		"footyear":   map[string]float64{"x": 365.0, "y": 304.0, "w": 135.0},
		"footmonth":  map[string]float64{"x": 420.0, "y": 304.0, "w": 105.0},
		"footday":    map[string]float64{"x": 450.0, "y": 304.0, "w": 105.0},
		"signature1": map[string]float64{"x": 390.0, "y": 250.0, "w": 85.0},
	}
	HetongPosition = map[string]map[string]float64{
		"contractNo":               map[string]float64{"x": 420.0, "y": 90.0, "w": 60.0},
		"hetongbianhao":            map[string]float64{"x": 450.0, "y": 105.0, "w": 60.0},
		"providerName":             map[string]float64{"x": 270.0, "y": 205.0, "w": 105.0},
		"providerAddr":             map[string]float64{"x": 165.0, "y": 237.0, "w": 105.0},
		"providerArtificialPerson": map[string]float64{"x": 165.0, "y": 268.0, "w": 105.0},
		"providerDelegatePerson":   map[string]float64{"x": 385.0, "y": 268.0, "w": 105.0},
		"providerContactNo":        map[string]float64{"x": 165.0, "y": 300.0, "w": 105.0},
		"providerComplaintNo":      map[string]float64{"x": 365.0, "y": 300.0, "w": 105.0},
		"providerSocialCreditCode": map[string]float64{"x": 200.0, "y": 330.0, "w": 105.0},
		"providerRodeBizCode":      {"x": 235.0, "y": 360.0, "w": 105.0},
		"consumerName":             map[string]float64{"x": 200.0, "y": 395.0, "w": 105.0},
		"consumerAddr":             map[string]float64{"x": 165.0, "y": 427.0, "w": 105.0},
		"consumerSex":              map[string]float64{"x": 165.0, "y": 458.0, "w": 105.0},
		"consumerContact":          map[string]float64{"x": 365.0, "y": 458.0, "w": 105.0},
		"consumerCardType":         map[string]float64{"x": 190.0, "y": 488.0, "w": 105.0},
		"consumerCardNo":           map[string]float64{"x": 365.0, "y": 488.0, "w": 105.0},

		"carType": map[string]float64{"x": 260.0, "y": 708.0, "w": 105.0},
		"carCode": map[string]float64{"x": 407.0, "y": 708.0, "w": 105.0},

		"contractServiceYear": {"x": 255.0, "y": 83.0, "w": 60.0}, // 合同自签订日起有效年数
		// 学时费用表格 - 科目一
		"subject1BasicClsHour": {"x": 160.0, "y": 357.0, "w": 60.0},
		"subject1BasicNetHour": {"x": 215.0, "y": 357.0, "w": 60.0},

		"subject1TrainClsHour": {"x": 160.0, "y": 380.0, "w": 60.0},
		"subject1TrainNetHour": {"x": 215.0, "y": 380.0, "w": 60.0},

		"subject1PriceClsHour": {"x": 160.0, "y": 405.0, "w": 60.0},
		"subject1PriceNetHour": {"x": 215.0, "y": 405.0, "w": 60.0},

		"subject1CostClsHour": {"x": 160.0, "y": 428.0, "w": 60.0},
		"subject1CostNetHour": {"x": 215.0, "y": 428.0, "w": 60.0},
		// 学时费用表格 - 科目二
		"subject2BasicClsHour": {"x": 265.0, "y": 357.0, "w": 60.0},
		"subject2BasicNetHour": {"x": 305.0, "y": 357.0, "w": 60.0},

		"subject2TrainClsHour": {"x": 265.0, "y": 380.0, "w": 60.0},
		"subject2TrainNetHour": {"x": 305.0, "y": 380.0, "w": 60.0},

		"subject2PriceClsHour": {"x": 265.0, "y": 405.0, "w": 60.0},
		"subject2PriceNetHour": {"x": 305.0, "y": 405.0, "w": 60.0},

		"subject2CostClsHour": {"x": 265.0, "y": 428.0, "w": 60.0}, // 科目二, 费用小计, 实际操做
		"subject2CostNetHour": {"x": 305.0, "y": 428.0, "w": 60.0}, // 科目二, 费用小计, 驾驶模拟器

		// 学时费用表格 - 科目三
		"subject3BasicClsHour": {"x": 348.0, "y": 357.0, "w": 60.0}, // 科目三, 基本学时, 实操
		"subject3BasicNetHour": {"x": 385.0, "y": 357.0, "w": 60.0}, // 科目三, 基本学时, 模拟

		"subject3TrainClsHour": {"x": 348.0, "y": 380.0, "w": 60.0}, // 科目三, 培训学时, 实际操做
		"subject3TrainNetHour": {"x": 385.0, "y": 380.0, "w": 60.0}, // 科目三, 培训学时, 驾驶模拟器

		"subject3PriceClsHour": {"x": 348.0, "y": 405.0, "w": 60.0}, // 科目三, 学时单价, 实际操做
		"subject3PriceNetHour": {"x": 385.0, "y": 405.0, "w": 60.0}, // 科目三, 学时单价, 驾驶模拟器

		"subject3CostClsHour": {"x": 348.0, "y": 428.0, "w": 60.0}, // 科目三, 费用小计, 实际操做
		"subject3CostNetHour": {"x": 385.0, "y": 428.0, "w": 60.0}, // 科目三, 费用小计, 驾驶模拟器

		// 学时费用表格 - 科目四
		"subject4BasicClsHour": {"x": 425.0, "y": 357.0, "w": 60.0}, // 科目四, 基本学时, 课堂教学
		"subject4BasicNetHour": {"x": 458.0, "y": 357.0, "w": 60.0}, // 科目四, 基本学时, 网络教学

		"subject4TrainClsHour": {"x": 425.0, "y": 380.0, "w": 60.0}, // 科目四, 培训学时, 课堂教学
		"subject4TrainNetHour": {"x": 458.0, "y": 380.0, "w": 60.0}, // 科目四, 培训学时, 网络教学

		"subject4PriceClsHour": {"x": 425.0, "y": 405.0, "w": 60.0}, // 科目四, 学时单价, 课堂教学
		"subject4PriceNetHour": {"x": 458.0, "y": 405.0, "w": 60.0}, // 科目四, 学时单价, 网络教学

		"subject4CostClsHour": {"x": 425.0, "y": 428.0, "w": 60.0}, // 科目四, 费用小计, 课堂教学
		"subject4CostNetHour": {"x": 458.0, "y": 428.0, "w": 60.0}, // 科目四, 费用小计, 网络教学

		"otherCost":      {"x": 175.0, "y": 455.0, "w": 60.0}, // 其他费用
		"totalCost":      {"x": 165.0, "y": 475.0, "w": 60.0}, // 费用总计 格式: 2位浮点数 例如: 0.00
		"totalCostYuan":  {"x": 325.0, "y": 475.0, "w": 60.0}, // 大写元
		"totalCostJiao":  {"x": 360.0, "y": 475.0, "w": 60.0}, // 大写角
		"totalCostFen":   {"x": 400.0, "y": 475.0, "w": 60.0}, // 大写分
		"serviceWaitDay": {"x": 285.0, "y": 560.0, "w": 60.0}, // 甲方应在乙方支付全部培训费用后{serviceWaitDay}日内提供培训服务。
		// 第四条 培训预约
		"consumerPickEnable":              {"x": 56.0, "y": 726.0, "w": 60.0},  // 乙方自主选择教练员、培训时间
		"providerChangeEnable":            {"x": 116.0, "y": 83.0, "w": 60.0},  // 甲方安排教练员并约定培训时间
		"consumerPreOrderDay":             {"x": 356.0, "y": 113.0, "w": 60.0}, // 乙方自主选择教练员、培训时间的，可提前N日进行预约
		"consumerPreOrderMethodWebEnable": {"x": 116.0, "y": 173.0, "w": 60.0}, // 支持互联网预约
		"consumerPreOrderMethodWebAddr":   {"x": 210.0, "y": 175.0, "w": 60.0}, // 互联网预约地址
		"consumerPreOrderMethodSchool":    {"x": 116.0, "y": 208.0, "w": 60.0}, // 支持甲方经营场所预约窗口
		"consumerPreOrderMethodOther":     {"x": 116.0, "y": 238.0, "w": 60.0}, // 支持其他方式预约
		"consumerPreOrderMethodOtherDesc": {"x": 196.0, "y": 238.0, "w": 60.0}, // 其他方式预约描述
		"consumerPreOrderCancelDayCount":  {"x": 250.0, "y": 268.0, "w": 60.0}, // 取消预约天数
		"consumerPreOrderCancelHourCount": {"x": 306.0, "y": 268.0, "w": 60.0}, // 取消预约小时

		// 第五条 甲方提供的培训服务地点(网址)
		"trainAddrClass":     {"x": 210.0, "y": 331.0, "w": 60.0}, // 课堂教学地点
		"trainAddrWeb":       {"x": 240.0, "y": 362.0, "w": 60.0}, // 远程网络教学网址
		"trainAddrSimulator": {"x": 270.0, "y": 392.0, "w": 60.0}, // “驾驶模拟器”培训地点
		"trainAddrSubject2":  {"x": 300.0, "y": 425.0, "w": 60.0}, // “基础和场地驾驶”培训地点
		"trainAddrSubject3":  {"x": 300.0, "y": 455.0, "w": 60.0}, // “道路驾驶”训练路线、区域

		// 第九条  甲方的违约责任
		"compensationHourNotEnough": {"x": 305.0, "y": 708.0, "w": 60.0}, // 学时不足, 甲方支付违约金 9条-1

		// 第九条  甲方的违约责任
		"compensationPreOrderFailed": {"x": 213.0, "y": 84.0, "w": 60.0},  // 预约未兑现, 甲方支付违约金 9条-2
		"compensationFake":           {"x": 205.0, "y": 145.0, "w": 60.0}, // 不符合规定, 甲方支付违约金 9条-3

		// 第十条  乙方的违约责任
		"compensationPreOrderError": {"x": 120.0, "y": 330.0, "w": 60.0}, // 乙方违规自主预约, 乙方支付违约金 10条-3

		// 第十三条  其他约定
		"item0": {"x": 128.0, "y": 80.0, "w": 60.0},
		"item1": {"x": 128.0, "y": 110.0, "w": 60.0},

		"copyTotalCount":    {"x": 310.0, "y": 175.0, "w": 60.0}, // 合同一式几份
		"providerCopyCount": {"x": 400.0, "y": 175.0, "w": 60.0}, // 甲方持有几份
		"consumerCopyCount": {"x": 478.0, "y": 175.0, "w": 60.0}, // 乙方持有几份

		"signproviderName":   {"x": 170.0, "y": 205.0, "w": 60.0}, // 甲方
		"signconsumerName":   {"x": 405.0, "y": 205.0, "w": 60.0}, // 乙方
		"delegatePersonName": {"x": 180.0, "y": 255.0, "w": 90.0}, // 法人或代理
		"signDate":           {"x": 390.0, "y": 360.0, "w": 60.0}, // 合同签订日期, YYYY-MM-dd
		"providerSeal":       {"x": 170.0, "y": 185.0, "w": 90.0}, // 甲方公章
		"studentSign":        {"x": 375.0, "y": 218.0, "w": 60.0}, // 乙方签名

	}
	jieYeData = map[string]map[string]float64{
		"number":      {"x": 210.0, "y": 70.0, "w": 105.0},
		"name":        {"x": 195.0, "y": 100.0, "w": 105},
		"sex":         {"x": 290.0, "y": 100.0, "w": 105.0},
		"sign_time":   {"x": 165.0, "y": 130.0, "w": 105.0},
		"end_time":    {"x": 285.0, "y": 130.0, "w": 105.0},
		"join_train":  {"x": 180.0, "y": 150.0, "w": 105.0},
		"join_train1": {"x": 180.0, "y": 160.0, "w": 105.0},
		"foot_time":   {"x": 325.0, "y": 225.0, "w": 105.0},
		"photo":       {"x": 385.0, "y": 60.0, "w": 60.0},
		"schoolname":  {"x": 325.0, "y": 200.0, "w": 105.0},
	}
)

func GetOssFile(fileurl string) (io.ReadCloser, error) {
	var (
		client *oss.Client
		bucket *oss.Bucket
		err    error
		u      *url.URL
	)
	// 上传到oss
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Println("配置文件载入错误")
	}

	ossSection, err := conf.GetSection("oss")
	if err != nil {
		log.Println("配置文件载入错误-数据库-section载入失败")
	}

	if client, err = oss.New(ossSection["oss_endpoint"], ossSection["oss_access_id"], ossSection["oss_access_key"]); err != nil {
		return nil, err
	}
	if bucket, err = client.Bucket(ossSection["oss_bucket"]); err != nil {
		return nil, err
	}
	if u, err = url.Parse(fileurl); err != nil {
		return nil, err
	}
	f, err := bucket.GetObject(u.Path[1:])
	//defer f.Close()
	return f, err
}

func loadFont(font string) error {
	if font == "" {
		font = "./static/fonts/stzhongs.ttf"
	}
	// 初始化字体
	fontBytes, err := ioutil.ReadFile(font)
	if err != nil {
		return err
	}
	fontTypes, err = freetype.ParseFont(fontBytes)
	if err != nil {
		return err
	}
	return nil
}

func openfile(s, p string) (*os.File, error) {
	var (
		f *os.File
		//buf *bytes.Buffer
	)
	//f := new(os.File)
	// if s == "./static/admin/pdf/stagetrainning.pdf" {
	// 	f, err := os.Open(s)
	// 	if err != nil {
	// 		return nil, err
	// 	}
	// 	//defer f.Close()
	// 	return f, nil
	// } else if s == "./static/admin/pdf/graduation.pdf" {
	// 	f, err := os.Open(s)
	// 	//defer f.Close()
	// 	if err != nil {
	// 		return nil, err
	// 	}
	// 	return f, nil
	// }
	// resp, err := http.Get(s)
	// if resp != nil {
	// 	defer resp.Body.Close()
	// }
	// if err != nil {
	// 	return nil, err
	// }
	rc, err := GetOssFile(s)

	if err != nil {
		return nil, err
	}
	filebyte, err := ioutil.ReadAll(rc)
	if err != nil {
		return nil, err
	}
	defer rc.Close()
	// w := bufio.NewWriter(f)
	// _, err = w.Write(filebyte)
	// if err != nil {
	// 	return nil, err
	// }
	// w.Flush()
	// return f, nil
	f, err = os.Create(p)
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(f, bytes.NewReader(filebyte))
	//_, err = f.Write(filebyte)
	if err != nil {
		return nil, err
	}
	return f, nil

}

func creatFile(ext, r string) (string, error) {
	t := time.Now().Unix()
	year := time.Now().Format("2006")
	month := time.Now().Format("01")
	day := time.Now().Format("02")
	upload_path := beego.AppConfig.String("upload")
	file_path := fmt.Sprintf("%s/%s/%s/%s/", upload_path, year, month, day)
	if err := os.MkdirAll(file_path, os.ModePerm); err != nil {
		return "", err
	}
	random := GetRandoms(10)
	outputPath := fmt.Sprintf("%s%d%s%s.%s", file_path, t, random, r, ext)
	return outputPath, nil
}

// CreateContract 生成电子合同
func CreateContractPdf(pdfURL string, m map[int]map[string]string, seal string) (string, error) {
	var (
		client *oss.Client
		bucket *oss.Bucket
	)
	resp, err := http.Get(pdfURL)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	br := bytes.NewReader(body)
	pdfReader, err := pdf.NewPdfReader(br)
	if err != nil {
		return "", err
	}

	numPages, err := pdfReader.GetNumPages()

	if err != nil {
		return "", err
	}
	d := creator.New()
	for i := 0; i < numPages; i++ {
		page, err := pdfReader.GetPage(i + 1)
		if err != nil {
			return "", err
		}

		err = d.AddPage(page)

		if err != nil {
			return "", err
		}
		if data, ok := m[i+1]; ok {
			for k, v := range data {
				var (
					fileData []byte
					width    int
				)
				if k == "studentSign" || k == "providerSeal" || k == "dailiZhang" || k == "delegatePersonName" {
					fileData, err = DrawPhoto(v)
					if err != nil {
						return "", err
					}
				} else if strings.Contains(k, "seal") {
					fileData, err = DrawSeal(seal)
					if err != nil {
						return "", err
					}
				} else {
					if len(v) == 0 {
						continue
					}
					fileData, width, err = drawPdfString(v)
					//fmt.Print(v,"vvvvvvvvvvvvvvvvvvvv",len(v))
					//fmt.Print("++++++++++++++++++++++++++++")
					if err != nil {
						return "", err
					}
				}
				img, err := creator.NewImageFromData(fileData)
				if err != nil {
					return "", err
				}
				img.SetPos(HetongPosition[k]["x"], HetongPosition[k]["y"])
				if k == "studentSign" || strings.Contains(k, "zhang") || strings.Contains(k, "Zhang") || k == "providerSeal" || k == "delegatePersonName" {
					img.ScaleToWidth(HetongPosition[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			}
		}

	}
	fileDir := fmt.Sprintf("%s/%s/%s/%s/", beego.AppConfig.String("upload"), time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	if err := os.MkdirAll(fileDir, os.ModePerm); err != nil {
		return "", err
	}
	var fileType string
	fileType = "h"
	fileName := fmt.Sprintf("%s/%s/%s/%s/%s%s.pdf", beego.AppConfig.String("upload"), time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"), m[1]["contractNo"], fileType)
	if err := d.WriteToFile(fileName); err != nil {
		return "", err
	}
	//if err := d.WriteToFile(fileName); err != nil {
	//	return "", err
	//}
	if client, err = oss.New(beego.AppConfig.String("oss_endpoint"), beego.AppConfig.String("oss_access_id"), beego.AppConfig.String("oss_access_key")); err != nil {
		fmt.Println(err.Error(), "12")
		//c.Resp(1, err.Error(), nil)
		return "", err
	}
	if bucket, err = client.Bucket(beego.AppConfig.String("oss_bucket")); err != nil {
		fmt.Println(err.Error(), "13")
		return "", err
	}
	// 构造文件名
	ossFileName := fmt.Sprintf("upload/%s/%s/%s%s.pdf", "epdfimg", time.Now().Format("20060102"), m[1]["contractNo"], fileType)
	if err := bucket.PutObjectFromFile(ossFileName, fileName); err != nil {
		return "", err
	}
	//defer f.Close()
	//os.Remove(fileName)
	return beego.AppConfig.String("oss_website") + ossFileName, nil
}

func CreatePdf(inputPath string, m map[string]string, types string, seal string) (string, error) {
	var (
		client *oss.Client
		bucket *oss.Bucket
	)
	resp, err := http.Get(inputPath)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	br := bytes.NewReader(body)
	pdfReader, err := pdf.NewPdfReader(br)
	if err != nil {
		return "", err
	}

	numPages, err := pdfReader.GetNumPages()

	if err != nil {
		return "", err
	}
	d := creator.New()
	for i := 0; i < numPages; i++ {
		page, err := pdfReader.GetPage(i + 1)
		if err != nil {
			return "", err
		}

		err = d.AddPage(page)

		if err != nil {
			return "", err
		}
		for k, v := range m {
			var (
				fileData []byte
				width    int
			)
			if k == "photo" {
				fileData, err = DrawJpeg(v)
				if err != nil {
					fmt.Println(err.Error(), "DrawJpeg")
					return "", err
				}
			} else if k == "faren" {
				fileData, err = DrawPhoto(v)
				if err != nil {
					return "", err
				}
			} else if k == "subject" || k == "institution_code" {
				continue
			} else if strings.Contains(k, "signature") {
				continue
			} else {
				fileData, width, err = drawString(v, types)
				if err != nil {
					fmt.Println(err.Error(), "drawString")
					return "", err
				}
			}
			img, err := creator.NewImageFromData(fileData)
			if err != nil {
				return "", err
			}
			if types == "r" {
				img.SetPos(StagePosition[k]["x"], StagePosition[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(StagePosition[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else if types == "h" {
				img.SetPos(HetongPosition[k]["x"], HetongPosition[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(StagePosition[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else if types == "t" {
				img.SetPos(jieYeData[k]["x"], jieYeData[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(jieYeData[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else {
				if inputPath == "http://oss.hahajishi.cn/graduation/shandong.pdf" {
					img.SetPos(ShanDongGraduationPosition[k]["x"], ShanDongGraduationPosition[k]["y"])
					if k == "province" {
						continue
					}
					if k == "photo" {
						img.ScaleToWidth(ShanDongGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 3.9)
					}
				} else if inputPath == "http://oss.hahajishi.cn/graduation/shanxi.pdf" {
					img.SetPos(ShanXiGraduationPosition[k]["x"], ShanXiGraduationPosition[k]["y"])
					if k == "province" || k == "signature1" || k == "school_name" {
						continue
					}
					if k == "photo" || k == "faren" {
						img.ScaleToWidth(ShanXiGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 4.1)
					}
				} else if inputPath == "http://oss.hahajishi.cn/graduation/chengdejieye.pdf" {
					img.SetPos(ChengDeGraduationPosition[k]["x"], ChengDeGraduationPosition[k]["y"])
					if k == "province" || k == "signature1" || k == "school_name" {
						continue
					}
					if k == "photo" {
						img.ScaleToWidth(ChengDeGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 4.1)
					}
				} else {
					img.SetPos(GraduationPosition[k]["x"], GraduationPosition[k]["y"])
					if k == "photo" {
						img.ScaleToWidth(GraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 3.9)
					}
				}
				d.Draw(img)
			}
		}
		for k, v := range m {
			if strings.Contains(k, "signature") {

				if len(v) > 0 {
					fileData, err := DrawSeal(seal)
					if err != nil {
						fmt.Println(err.Error(), "DrawSeal")
						return "", err
					}
					img, err := creator.NewImageFromData(fileData)
					if err != nil {
						return "", err
					}
					if types == "r" {
						img.SetPos(StagePosition[k]["x"], StagePosition[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(StagePosition[k]["w"])
						}
						d.Draw(img)
					} else if types == "h" {
						img.SetPos(HetongPosition[k]["x"], HetongPosition[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(StagePosition[k]["w"])
						}
						d.Draw(img)
					} else if types == "t" {
						img.SetPos(jieYeData[k]["x"], jieYeData[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(jieYeData[k]["w"])
						}
						d.Draw(img)
					} else {
						if inputPath == "http://oss.hahajishi.cn/graduation/shandong.pdf" {
							img.SetPos(ShanDongGraduationPosition[k]["x"], ShanDongGraduationPosition[k]["y"])
							if k == "province" {
								continue
							}
							if strings.Contains(k, "signature") {
								img.ScaleToWidth(ShanDongGraduationPosition[k]["w"])
							}
							d.Draw(img)
						} else {
							img.SetPos(GraduationPosition[k]["x"], GraduationPosition[k]["y"])
							if strings.Contains(k, "signature") {
								img.ScaleToWidth(GraduationPosition[k]["w"])
							}
							d.Draw(img)
						}
					}
				}
			}
		}
	}
	fileDir := fmt.Sprintf("%s/%s/%s/%s/", "./static/upload", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	if err := os.MkdirAll(fileDir, os.ModePerm); err != nil {
		return "", err
	}
	var fileType string
	if types == "r" {
		fileType = m["subject"]
	} else if types == "t" {
		fileType = "t"
	} else {
		fileType = "g"
	}
	fileName := fmt.Sprintf("%s/%s/%s/%s/%s%s.pdf", "./static/upload", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"), m["institution_code"], fileType)
	if err := d.WriteToFile(fileName); err != nil {
		return "", err
	}
	// 上传到oss
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Println("配置文件载入错误")
	}

	ossSection, err := conf.GetSection("oss")
	if err != nil {
		log.Println("配置文件载入错误-数据库-section载入失败")
	}
	if client, err = oss.New(ossSection["oss_endpoint"], ossSection["oss_access_id"], ossSection["oss_access_key"]); err != nil {
		return "", err
	}
	if bucket, err = client.Bucket(ossSection["oss_bucket"]); err != nil {
		return "", err
	}
	// 构造文件名
	ossFileName := fmt.Sprintf("upload/%s/%s/%s%s.pdf", "epdfimg", time.Now().Format("20060102"), m["institution_code"], fileType)
	if err := bucket.PutObjectFromFile(ossFileName, fileName); err != nil {
		return "", err
	}
	//defer f.Close()
	//os.Remove(fileName)
	return ossSection["oss_website"] + ossFileName, nil
}

// DrawJpegNew 阶段PDF头像设置尺寸
func DrawJpegNew(fileUrl string) ([]byte, error) {
	var (
		buf bytes.Buffer
	)

	resp, err := http.Get(fileUrl)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	img, err := jpeg.Decode(resp.Body)
	img = (*image.RGBA)(imaging.Fill(img, 800, 1000, imaging.Center, imaging.Lanczos))
	if err != nil {
		return nil, err
	}
	//png.Encode(&buf, img)
	jpeg.Encode(&buf, img, &jpeg.Options{8})
	return buf.Bytes(), nil
}

// DrawJpeg 将图片
func DrawJpeg(fileUrl string) ([]byte, error) {
	var (
		buf bytes.Buffer
	)

	resp, err := http.Get(fileUrl)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	img, err := jpeg.Decode(resp.Body)

	if err != nil {
		return nil, err
	}
	//png.Encode(&buf, img)
	jpeg.Encode(&buf, img, &jpeg.Options{8})
	return buf.Bytes(), nil
}

// DrawPhoto
func DrawPhoto(fileUrl string) ([]byte, error) {
	var (
		buf bytes.Buffer
	)
	resp, err := http.Get(fileUrl)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	img, err := png.Decode(resp.Body)
	if err != nil {
		return nil, err
	}
	//img, err := jpeg.Decode(resp.Body)

	png.Encode(&buf, img)
	//jpeg.Encode(&buf, img, &jpeg.Options{8})
	return buf.Bytes(), nil
}

// DrawSeal 插入章
func DrawSeal(seal string) ([]byte, error) {
	var (
		buf  bytes.Buffer
		data []byte
		err  error
	)
	data, err = hex.DecodeString(seal)
	if err != nil {
		data, err = base64.StdEncoding.DecodeString(seal)
		if err != nil {
			return nil, err
		}
		// return nil, err
	}
	r := bytes.NewReader(data)
	img, err := png.Decode(r)
	if err != nil {
		return nil, err
	}

	m := resize.Resize(100, 100, img, resize.Bicubic)
	png.Encode(&buf, m)
	return buf.Bytes(), nil
}

//func procPage(page *unipdf.PdfPage, m map[string]string, types string, seal string) error {
//
//	for k, v := range m {
//		if k == "photo" {
//			err := drawPhoto(k, v, page, types)
//			if err != nil {
//				fmt.Println("1", err.Error())
//				return err
//			}
//			continue
//
//		}
//		if k == "signature1" || k == "signature2" || k == "signature3" || k == "signature4" {
//			err := drawSeal(k, page, types, seal)
//			if err != nil {
//				fmt.Println("2", err.Error())
//				return err
//			}
//			continue
//		}
//		err := drawString(k, v, page, types)
//		if err != nil {
//			fmt.Println("3", err.Error())
//			return err
//		}
//	}
//	return nil
//
//}

func drawPdfString(v string) (data []byte, w int, err error) {
	var (
		buf      bytes.Buffer
		fontSize = 30
	)
	if fontTypes == nil {
		if err := loadFont(""); err != nil {
			return nil, 0, err
		}
	}
	rgba := image.NewRGBA(image.Rect(0, 0, int(fontSize)*len(v), int(fontSize)+10))
	c := freetype.NewContext()
	c.SetFont(fontTypes)
	c.SetFontSize(float64(fontSize))
	c.SetClip(rgba.Bounds())
	c.SetDst(rgba)
	c.SetSrc(image.Black)
	// Draw the text.
	pt := freetype.Pt(0, int(c.PointToFixed(float64(fontSize))>>6))
	_, err = c.DrawString(v, pt)
	if err != nil {
		return nil, 0, err
	}
	if err := png.Encode(&buf, rgba); err != nil {
		return nil, 0, err
	}
	return buf.Bytes(), rgba.Bounds().Dx(), nil
}

func drawString(v, types string) (data []byte, w int, err error) {
	var (
		buf      bytes.Buffer
		fontSize = 40
	)
	if types == "t" {
		fontSize = 30
	}
	if fontTypes == nil {
		if err := loadFont(""); err != nil {
			return nil, 0, err
		}
	}
	rgba := image.NewRGBA(image.Rect(0, 0, int(fontSize)*len(v), int(fontSize)+10))
	c := freetype.NewContext()
	c.SetFont(fontTypes)
	c.SetFontSize(float64(fontSize))
	c.SetClip(rgba.Bounds())
	c.SetDst(rgba)
	c.SetSrc(image.Black)
	// Draw the text.
	pt := freetype.Pt(0, int(c.PointToFixed(float64(fontSize))>>6))
	_, err = c.DrawString(v, pt)
	if err != nil {
		return nil, 0, err
	}
	if err := png.Encode(&buf, rgba); err != nil {
		return nil, 0, err
	}
	return buf.Bytes(), rgba.Bounds().Dx(), nil
}

//func drawString(k, v string, page *unipdf.PdfPage, types string) error {
//	var (
//		buf, bufGray bytes.Buffer
//		opt          = jpeg.Options{Quality: 100}
//		tangle       map[string]unipdf.PdfRectangle
//	)
//	rgba := image.NewRGBA(image.Rect(0, 0, int(fontSize)*len(v), int(fontSize)+10))
//	//draw.Draw(rgba, rgba.Bounds(), image.White, image.ZP, draw.Src)
//
//	c := freetype.NewContext()
//	c.SetFont(fontTypes)
//	c.SetFontSize(fontSize)
//	c.SetClip(rgba.Bounds())
//	c.SetDst(rgba)
//	c.SetSrc(image.Black)
//
//	// Draw the text.
//	pt := freetype.Pt(0, int(c.PointToFixed(fontSize)>>6))
//	r, err := c.DrawString(v, pt)
//	if err != nil {
//		return err
//	}
//
//	b := image.Rect(0, 0, int(r.X>>6)+5, int(fontSize)+5)
//	rgbab := rgba.SubImage(b)
//	gray := image.NewGray(b)
//
//	for x := 0; x < b.Max.X; x++ {
//		for y := 0; y < b.Max.Y; y++ {
//			oldColor := rgbab.At(x, y)
//			_, _, _, a := oldColor.RGBA()
//			gray.SetGray(x, y, color.Gray{Y: uint8(a)})
//		}
//	}
//
//	err = jpeg.Encode(&bufGray, gray, &opt)
//
//	//err = jpeg.Encode(&buf, rgba.SubImage(b), &opt)
//	if err != nil {
//		return err
//	}
//
//	imgGray := unipdf.Image{Width: int64(b.Dx()), Height: int64(b.Dy()), Data: &bufGray}
//	imgNameGray := unipdf.PdfObjectName(fmt.Sprintf("Img%sGray", k))
//	ximgGray, err := unipdf.NewXObjectImage(imgNameGray, &imgGray)
//	if err != nil {
//		return err
//	}
//	ximgGray.ColorSpace = unipdf.MakeName("DeviceGray")
//	page.AddImageResource(imgNameGray, ximgGray)
//
//	err = jpeg.Encode(&buf, rgbab, &opt)
//	if err != nil {
//		return err
//	}
//
//	/*
//		b := image.Rect(0, 0, int(r.X>>6)+5, int(fontSize)+5)
//		err = jpeg.Encode(&buf, rgba.SubImage(b), &opt)
//		if err != nil {
//			return err
//		}
//	*/
//	img := unipdf.Image{Width: int64(b.Dx()), Height: int64(b.Dy()), Data: &buf}
//	imgName := unipdf.PdfObjectName(fmt.Sprintf("Img%s", k))
//	ximg, err := unipdf.NewXObjectImage(imgName, &img)
//	if err != nil {
//		return err
//	}
//	if xresDict, ok := (page.Resources.XObject).(*unipdf.PdfObjectDictionary); ok {
//		ximg.SMask = (*xresDict)[imgNameGray]
//	}
//
//	// put image to pdf page
//	/*
//		img := unipdf.Image{Width: int64(b.Dx()), Height: int64(b.Dy()), Data: &buf}
//		imgName := unipdf.PdfObjectName(fmt.Sprintf("Img%s", k))
//		ximg, err := unipdf.NewXObjectImage(imgName, &img)
//		if err != nil {
//			return err
//		}
//	*/
//	tangle = make(map[string]unipdf.PdfRectangle)
//
//	if types == "r" {
//		tangle = rectang
//		if beego.BConfig.RunMode == "liaoning" {
//			tangle["signature1"] = unipdf.PdfRectangle{Llx: 100, Lly: 0, Urx: 510, Ury: 306}
//			tangle["signature2"] = unipdf.PdfRectangle{Llx: 100, Lly: 0, Urx: 510, Ury: 236}
//			tangle["signature3"] = unipdf.PdfRectangle{Llx: 100, Lly: 0, Urx: 510, Ury: 166}
//			tangle["signature4"] = unipdf.PdfRectangle{Llx: 100, Lly: 0, Urx: 510, Ury: 95}
//		}
//	} else {
//		tangle = gradtang
//	}
//
//	page.AddImageResource(imgName, ximg)
//	page.AddContentStreamByString(fmt.Sprintf("q\n"+
//		"%d 0 0 %d %.0f %.0f cm\n"+
//		"/%s Do\n"+
//		"Q", img.Width, img.Height, tangle[k].Urx, tangle[k].Ury, imgName))
//
//	return nil
//}

func GetRandoms(lens int64) string {
	var i int64
	var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	//时间戳+n位随机数字
	timestr := strconv.FormatInt(time.Now().Unix(), 10)
	leftlens := lens - int64(len(timestr))
	if leftlens < 5 {
		leftlens = 5
	}

	for i = 0; i < leftlens; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return timestr + string(result)
}

func CreateNewPdf(inputPath string, m map[string]string, types string, seal string) (string, error) {
	var (
		client *oss.Client
		bucket *oss.Bucket
	)
	resp, err := http.Get(inputPath)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	br := bytes.NewReader(body)
	pdfReader, err := pdf.NewPdfReader(br)
	if err != nil {
		return "", err
	}

	numPages, err := pdfReader.GetNumPages()

	if err != nil {
		return "", err
	}
	d := creator.New()
	for i := 0; i < numPages; i++ {
		page, err := pdfReader.GetPage(i + 1)
		if err != nil {
			return "", err
		}

		err = d.AddPage(page)

		if err != nil {
			return "", err
		}
		for k, v := range m {
			var (
				fileData []byte
				width    int
			)
			if k == "photo" {
				fileData, err = DrawJpegNew(v)
				if err != nil {
					fmt.Println(err.Error(), "DrawJpeg")
					return "", err
				}
			} else if k == "A1" || k == "A2" || k == "A3" || k == "B1" || k == "B2" || k == "C1" || k == "C2" || k == "C3" || k == "C4" || k == "C5" || k == "C6" || k == "D" || k == "E" || k == "F" || k == "M" || k == "N" || k == "P" {
				fileData, err = DrawJpeg(v)
				if err != nil {
					fmt.Println(err.Error(), "DrawJpeg")
					return "", err
				}
			} else if k == "faren" {
				fileData, err = DrawPhoto(v)
				if err != nil {
					return "", err
				}
			} else if k == "subject" || k == "institution_code" {
				continue
			} else if strings.Contains(k, "signature") {
				continue
			} else {
				fileData, width, err = drawString(v, types)
				if err != nil {
					fmt.Println(err.Error(), "drawString")
					return "", err
				}
			}
			img, err := creator.NewImageFromData(fileData)
			if err != nil {
				return "", err
			}
			if types == "r" {
				img.SetPos(NewStagePosition[k]["x"], NewStagePosition[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(NewStagePosition[k]["w"])
				} else if k == "A1" || k == "A2" || k == "A3" || k == "B1" || k == "B2" || k == "C1" || k == "C2" || k == "C3" || k == "C4" || k == "C5" || k == "C6" || k == "D" || k == "E" || k == "F" || k == "M" || k == "N" || k == "P" {
					img.ScaleToWidth(NewStagePosition[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else if types == "h" {
				img.SetPos(HetongPosition[k]["x"], HetongPosition[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(StagePosition[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else if types == "t" {
				img.SetPos(jieYeData[k]["x"], jieYeData[k]["y"])
				if k == "photo" {
					img.ScaleToWidth(jieYeData[k]["w"])
				} else {
					img.ScaleToWidth(float64(width) / 3.9)
				}
				d.Draw(img)
			} else {
				if inputPath == "http://oss.hahajishi.cn/graduation/shandong.pdf" {
					img.SetPos(ShanDongGraduationPosition[k]["x"], ShanDongGraduationPosition[k]["y"])
					if k == "province" {
						continue
					}
					if k == "photo" {
						img.ScaleToWidth(ShanDongGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 3.9)
					}
				} else if inputPath == "http://oss.hahajishi.cn/graduation/shanxi.pdf" {
					img.SetPos(ShanXiGraduationPosition[k]["x"], ShanXiGraduationPosition[k]["y"])
					if k == "province" || k == "signature1" || k == "school_name" {
						continue
					}
					if k == "photo" || k == "faren" {
						img.ScaleToWidth(ShanXiGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 4.1)
					}
				} else if inputPath == "http://oss.hahajishi.cn/graduation/chengdejieye.pdf" {
					img.SetPos(ChengDeGraduationPosition[k]["x"], ChengDeGraduationPosition[k]["y"])
					if k == "province" || k == "signature1" || k == "school_name" {
						continue
					}
					if k == "photo" {
						img.ScaleToWidth(ChengDeGraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 4.1)
					}
				} else {
					img.SetPos(GraduationPosition[k]["x"], GraduationPosition[k]["y"])
					if k == "photo" {
						img.ScaleToWidth(GraduationPosition[k]["w"])
					} else {
						img.ScaleToWidth(float64(width) / 3.9)
					}
				}
				d.Draw(img)
			}
		}
		for k, v := range m {
			if strings.Contains(k, "signature") {

				if len(v) > 0 {
					fileData, err := DrawSeal(seal)
					if err != nil {
						fmt.Println(err.Error(), "DrawSeal")
						return "", err
					}
					img, err := creator.NewImageFromData(fileData)
					if err != nil {
						return "", err
					}
					if types == "r" {
						img.SetPos(StagePosition[k]["x"], StagePosition[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(StagePosition[k]["w"])
						}
						d.Draw(img)
					} else if types == "h" {
						img.SetPos(HetongPosition[k]["x"], HetongPosition[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(StagePosition[k]["w"])
						}
						d.Draw(img)
					} else if types == "t" {
						img.SetPos(jieYeData[k]["x"], jieYeData[k]["y"])
						if strings.Contains(k, "signature") {
							img.ScaleToWidth(jieYeData[k]["w"])
						}
						d.Draw(img)
					} else {
						if inputPath == "http://oss.hahajishi.cn/graduation/shandong.pdf" {
							img.SetPos(ShanDongGraduationPosition[k]["x"], ShanDongGraduationPosition[k]["y"])
							if k == "province" {
								continue
							}
							if strings.Contains(k, "signature") {
								img.ScaleToWidth(ShanDongGraduationPosition[k]["w"])
							}
							d.Draw(img)
						} else {
							img.SetPos(GraduationPosition[k]["x"], GraduationPosition[k]["y"])
							if strings.Contains(k, "signature") {
								img.ScaleToWidth(GraduationPosition[k]["w"])
							}
							d.Draw(img)
						}
					}
				}
			}
		}
	}

	fileDir := fmt.Sprintf("%s/%s/%s/%s/", beego.AppConfig.String("upload"), time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	if err := os.MkdirAll(fileDir, os.ModePerm); err != nil {
		return "", err
	}
	var fileType string
	if types == "r" {
		fileType = m["subject"]
	} else if types == "t" {
		fileType = "t"
	} else {
		fileType = "g"
	}
	fileName := fmt.Sprintf("%s/%s/%s/%s/%s%s.pdf", beego.AppConfig.String("upload"), time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"), m["institution_code"], fileType)
	if err := d.WriteToFile(fileName); err != nil {
		return "", err
	}
	// 上传到oss
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Println("配置文件载入错误")
	}

	ossSection, err := conf.GetSection("oss")
	if err != nil {
		log.Println("配置文件载入错误-数据库-section载入失败")
	}

	if client, err = oss.New(ossSection["oss_endpoint"], ossSection["oss_access_id"], ossSection["oss_access_key"]); err != nil {
		return "", err
	}
	if bucket, err = client.Bucket(ossSection["oss_bucket"]); err != nil {
		return "", err
	}
	// 构造文件名
	ossFileName := fmt.Sprintf("upload/%s/%s/%s%s.pdf", "epdfimg", time.Now().Format("20060102"), m["institution_code"], fileType)
	if err := bucket.PutObjectFromFile(ossFileName, fileName); err != nil {
		return "", err
	}
	//defer f.Close()
	//os.Remove(fileName)
	return ossSection["oss_website"] + ossFileName, nil
}
